from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, StreamingResponse
from sqlalchemy.orm import Session
from datetime import timedelta
from typing import List
import os
import json
import asyncio
from concurrent.futures import ThreadPoolExecutor

from config import settings
from database import get_db, engine
from models import Base, User, FortuneRecord
from schemas import (
    UserCreate, User as UserSchema, UserLogin, Token,
    FortuneRecordCreate, FortuneRecord as FortuneRecordSchema,
    BaziCalculationRequest, BaziResult, AIQuestionRequest, AIQuestionResponse
)
from auth import (
    authenticate_user, create_access_token, get_current_active_user,
    get_password_hash, get_user
)
from bazi_calculator import BaziCalculator
from openai_service import OpenAIService
from city_data import get_city_coordinates, get_provinces, get_cities

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 创建 FastAPI 应用
app = FastAPI(
    title=settings.APP_NAME,
    description="基于 OpenAI 和 FastAPI 的生辰八字算命应用系统",
    version="1.0.0"
)

# 挂载静态文件
if not os.path.exists("static"):
    os.makedirs("static")
app.mount("/static", StaticFiles(directory="static"), name="static")

# 初始化服务
bazi_calculator = BaziCalculator()
openai_service = OpenAIService()

# 创建线程池用于执行同步的 OpenAI 流式响应
executor = ThreadPoolExecutor(max_workers=5)

@app.get("/", response_class=HTMLResponse)
async def read_root():
    """返回主页"""
    return """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>AI 生辰八字算命系统</title>
        <link rel="stylesheet" href="/static/style.css">
    </head>
    <body>
        <div class="container">
            <header>
                <h1>AI 生辰八字算命系统</h1>
                <p>基于传统命理学与现代 AI 技术的智能算命平台</p>
            </header>
            
            <main>
                <div class="auth-section">
                    <div class="auth-tabs">
                        <button class="tab-btn active" onclick="showTab('login')">登录</button>
                        <button class="tab-btn" onclick="showTab('register')">注册</button>
                    </div>
                    
                    <div id="login-form" class="auth-form active">
                        <h2>用户登录</h2>
                        <form onsubmit="login(event)">
                            <div class="form-group">
                                <label for="login-username">用户名</label>
                                <input type="text" id="login-username" required>
                            </div>
                            <div class="form-group">
                                <label for="login-password">密码</label>
                                <input type="password" id="login-password" required>
                            </div>
                            <button type="submit" class="btn-primary">登录</button>
                        </form>
                    </div>
                    
                    <div id="register-form" class="auth-form">
                        <h2>用户注册</h2>
                        <form onsubmit="register(event)">
                            <div class="form-group">
                                <label for="reg-username">用户名</label>
                                <input type="text" id="reg-username" required>
                            </div>
                            <div class="form-group">
                                <label for="reg-email">邮箱</label>
                                <input type="email" id="reg-email" required>
                            </div>
                            <div class="form-group">
                                <label for="reg-password">密码</label>
                                <input type="password" id="reg-password" required>
                            </div>
                            <button type="submit" class="btn-primary">注册</button>
                        </form>
                    </div>
                </div>
                
                <div id="main-app" class="main-app" style="display: none;">
                    <div class="user-info">
                        <span id="welcome-msg"></span>
                        <button onclick="logout()" class="btn-secondary">退出登录</button>
                    </div>
                    
                    <div class="fortune-section">
                        <h2>🎋 生辰八字算命</h2>
                        <form onsubmit="calculateFortune(event)" id="fortune-form">
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="name">姓名 <span class="optional">(选填)</span></label>
                                    <input type="text" id="name" placeholder="请输入姓名">
                                </div>
                                <div class="form-group">
                                    <label for="gender">性别 <span class="optional">(选填)</span></label>
                                    <select id="gender">
                                        <option value="">请选择性别</option>
                                        <option value="男">男</option>
                                        <option value="女">女</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="birth-year">出生年份</label>
                                    <select id="birth-year" required>
                                        <option value="">请选择年份</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="birth-month">出生月份</label>
                                    <select id="birth-month" required>
                                        <option value="">请选择月份</option>
                                        <option value="1">1月</option>
                                        <option value="2">2月</option>
                                        <option value="3">3月</option>
                                        <option value="4">4月</option>
                                        <option value="5">5月</option>
                                        <option value="6">6月</option>
                                        <option value="7">7月</option>
                                        <option value="8">8月</option>
                                        <option value="9">9月</option>
                                        <option value="10">10月</option>
                                        <option value="11">11月</option>
                                        <option value="12">12月</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="birth-day">出生日期</label>
                                    <select id="birth-day" required>
                                        <option value="">请选择日期</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="birth-time">出生时间</label>
                                    <div class="time-input-group">
                                        <select id="birth-hour" required class="time-select">
                                            <option value="">时</option>
                                            <option value="0">00</option>
                                            <option value="1">01</option>
                                            <option value="2">02</option>
                                            <option value="3">03</option>
                                            <option value="4">04</option>
                                            <option value="5">05</option>
                                            <option value="6">06</option>
                                            <option value="7">07</option>
                                            <option value="8">08</option>
                                            <option value="9">09</option>
                                            <option value="10">10</option>
                                            <option value="11">11</option>
                                            <option value="12">12</option>
                                            <option value="13">13</option>
                                            <option value="14">14</option>
                                            <option value="15">15</option>
                                            <option value="16">16</option>
                                            <option value="17">17</option>
                                            <option value="18">18</option>
                                            <option value="19">19</option>
                                            <option value="20">20</option>
                                            <option value="21">21</option>
                                            <option value="22">22</option>
                                            <option value="23">23</option>
                                        </select>
                                        <span class="time-separator">:</span>
                                        <select id="birth-minute" required class="time-select">
                                            <option value="">分</option>
                                        </select>
                                    </div>
                                    <small class="form-hint">参考时辰：子时(23-1)、丑时(1-3)、寅时(3-5)、卯时(5-7)、辰时(7-9)、巳时(9-11)、午时(11-13)、未时(13-15)、申时(15-17)、酉时(17-19)、戌时(19-21)、亥时(21-23)</small>
                                </div>
                                <div class="form-group">
                                    <label for="birth-province">出生省份 <span class="optional">(选填)</span></label>
                                    <select id="birth-province">
                                        <option value="">请选择省份</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="birth-city">出生城市 <span class="optional">(选填)</span></label>
                                    <select id="birth-city" disabled>
                                        <option value="">请先选择省份</option>
                                    </select>
                                    <small class="form-hint">选择城市后会自动使用该城市的经度计算真太阳时，未选择则使用北京经度</small>
                                </div>
                            </div>
                            <button type="submit" class="btn-primary">✨ 第一阶段：计算八字</button>
                        </form>
                    </div>
                    
                    <div id="result-section" class="result-section" style="display: none;">
                        <div id="stage1-result">
                            <h3>📊 八字计算结果</h3>
                            <div id="bazi-result"></div>
                            <button id="btn-analyze" class="btn-secondary" style="display: none; margin-top: 20px; width: 100%;">
                                🎯 第二阶段：AI智能分析（婚嫁、事业）
                            </button>
                        </div>
                        <div id="stage2-result" style="display: none;">
                            <h3>🤖 AI智能分析</h3>
                            <div style="display:flex; gap:10px; margin:10px 0 20px 0; flex-wrap: wrap;">
                                <button id="btn-copy-md" class="btn-secondary" onclick="copyAnalysisMarkdown()">📋 一键复制 Markdown</button>
                                <button id="btn-export-pdf" class="btn-secondary" onclick="exportAnalysisPDF()">🧾 导出为 PDF</button>
                            </div>
                            <div id="ai-analysis"></div>
                            <div id="ai-qa-section" style="margin-top: 30px;">
                                <h4>💬 继续提问</h4>
                                <div class="qa-container">
                                    <input type="text" id="ai-question-input" placeholder="可以问我关于婚嫁、事业等问题..." class="qa-input">
                                    <button onclick="askAIQuestion()" class="btn-primary qa-btn">提问</button>
                                </div>
                                <div id="qa-questions" class="qa-questions"></div>
                                <div id="qa-suggestions" class="qa-suggestions">
                                    <p>💡 试试这些问题：</p>
                                    <button class="qa-suggestion-btn" onclick="quickQuestion('我的婚姻运势如何？')">我的婚姻运势如何？</button>
                                    <button class="qa-suggestion-btn" onclick="quickQuestion('我适合什么职业？')">我适合什么职业？</button>
                                    <button class="qa-suggestion-btn" onclick="quickQuestion('什么时候会有好的事业机会？')">什么时候会有好的事业机会？</button>
                                    <button class="qa-suggestion-btn" onclick="quickQuestion('我的财运怎么样？')">我的财运怎么样？</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="history-section">
                        <h3>历史记录</h3>
                        <div id="history-list"></div>
                    </div>
                </div>
            </main>
        </div>
        
        <script src="/static/script.js"></script>
    </body>
    </html>
    """

# 用户注册
@app.post("/register", response_model=UserSchema)
async def register(user: UserCreate, db: Session = Depends(get_db)):
    """用户注册"""
    # 检查用户名是否已存在
    if get_user(db, user.username):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )
    
    # 检查邮箱是否已存在
    if db.query(User).filter(User.email == user.email).first():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="邮箱已被注册"
        )
    
    # 创建新用户
    hashed_password = get_password_hash(user.password)
    db_user = User(
        username=user.username,
        email=user.email,
        hashed_password=hashed_password
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    return db_user

# 用户登录
@app.post("/login", response_model=Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """用户登录"""
    user = authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    
    return {"access_token": access_token, "token_type": "bearer"}

# 获取当前用户信息
@app.get("/me", response_model=UserSchema)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
    """获取当前用户信息"""
    return current_user

# 获取省份列表
@app.get("/provinces")
async def get_provinces_list():
    """获取所有省份列表"""
    return {"provinces": get_provinces()}

# 获取城市列表
@app.get("/cities/{province}")
async def get_cities_list(province: str):
    """获取指定省份的城市列表"""
    cities = get_cities(province)
    return {"cities": cities}

# 第一阶段：计算生辰八字
@app.post("/calculate-bazi", response_model=BaziResult)
async def calculate_bazi(
    request: BaziCalculationRequest,
    current_user: User = Depends(get_current_active_user)
):
    """第一阶段：计算生辰八字（使用真太阳时）"""
    # 获取经度：优先使用城市，其次使用手动输入的经度，最后默认北京
    longitude = 116.4  # 默认北京经度
    if request.province and request.city:
        # 通过城市获取经纬度
        coords = get_city_coordinates(request.province, request.city)
        longitude = coords[0]  # 经度
    elif request.longitude is not None:
        longitude = request.longitude
    
    # 计算八字（使用真太阳时）
    bazi_data = bazi_calculator.calculate_bazi(
        request.birth_year, request.birth_month, 
        request.birth_day, request.birth_hour, request.birth_minute,
        use_solar_time=True, longitude=longitude
    )
    
    # 分析五行
    five_elements = bazi_calculator.get_five_elements_analysis(bazi_data)
    
    # 生成分析文本
    analysis = f"""
    您的生辰八字为：
    年柱：{bazi_data['year_pillar']}
    月柱：{bazi_data['month_pillar']}
    日柱：{bazi_data['day_pillar']}
    时柱：{bazi_data['hour_pillar']}
    
    五行分布：木{five_elements['木']}个，火{five_elements['火']}个，土{five_elements['土']}个，金{five_elements['金']}个，水{five_elements['水']}个
    """
    
    return BaziResult(
        year_pillar=bazi_data['year_pillar'],
        month_pillar=bazi_data['month_pillar'],
        day_pillar=bazi_data['day_pillar'],
        hour_pillar=bazi_data['hour_pillar'],
        five_elements=five_elements,
        analysis=analysis,
        solar_year=bazi_data.get('solar_year'),
        solar_month=bazi_data.get('solar_month'),
        solar_day=bazi_data.get('solar_day'),
        solar_hour=bazi_data.get('solar_hour'),
        solar_minute=bazi_data.get('solar_minute')
    )

# 第一阶段：保存算命记录（仅计算八字）
@app.post("/save-fortune-record", response_model=FortuneRecordSchema)
async def save_fortune_record(
    record: FortuneRecordCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """第一阶段：保存算命记录（仅计算八字，不进行AI分析）"""
    # 获取经度：优先使用城市，其次使用手动输入的经度，最后默认北京
    longitude = 116.4  # 默认北京经度
    if record.province and record.city:
        # 通过城市获取经纬度
        coords = get_city_coordinates(record.province, record.city)
        longitude = coords[0]  # 经度
    elif record.longitude is not None:
        longitude = record.longitude
    longitude_str = str(longitude) if longitude else None
    
    # 计算八字（使用真太阳时）
    bazi_data = bazi_calculator.calculate_bazi(
        record.birth_year, record.birth_month,
        record.birth_day, record.birth_hour, record.birth_minute,
        use_solar_time=True, longitude=longitude
    )
    
    # 创建记录（第一阶段，stage=1）
    db_record = FortuneRecord(
        user_id=current_user.id,
        name=record.name,
        gender=record.gender,
        birth_year=record.birth_year,
        birth_month=record.birth_month,
        birth_day=record.birth_day,
        birth_hour=record.birth_hour,
        birth_minute=record.birth_minute,
        longitude=longitude_str,
        province=record.province,
        city=record.city,
        solar_year=bazi_data.get('solar_year'),
        solar_month=bazi_data.get('solar_month'),
        solar_day=bazi_data.get('solar_day'),
        solar_hour=bazi_data.get('solar_hour'),
        solar_minute=bazi_data.get('solar_minute'),
        year_pillar=bazi_data['year_pillar'],
        month_pillar=bazi_data['month_pillar'],
        day_pillar=bazi_data['day_pillar'],
        hour_pillar=bazi_data['hour_pillar'],
        stage=1  # 第一阶段
    )
    
    db.add(db_record)
    db.commit()
    db.refresh(db_record)
    
    return db_record

# 第二阶段：进行AI分析（流式）
@app.post("/analyze-fortune/{record_id}/stream")
async def analyze_fortune_stream(
    record_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """第二阶段：对已保存的记录进行AI分析（流式响应）"""
    # 获取记录
    record = db.query(FortuneRecord).filter(
        FortuneRecord.id == record_id,
        FortuneRecord.user_id == current_user.id
    ).first()
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="记录不存在"
        )
    
    # 如果已经分析过，返回已有内容
    if record.stage == 2 and record.ai_analysis:
        async def send_existing():
            yield f"data: {json.dumps({'type': 'content', 'text': record.ai_analysis})}\n\n"
            yield f"data: {json.dumps({'type': 'done'})}\n\n"
        return StreamingResponse(send_existing(), media_type="text/event-stream")
    
    # 准备八字数据
    bazi_data = {
        'year_pillar': record.year_pillar,
        'month_pillar': record.month_pillar,
        'day_pillar': record.day_pillar,
        'hour_pillar': record.hour_pillar
    }
    
    # 分析五行
    five_elements = bazi_calculator.get_five_elements_analysis(bazi_data)
    
    # 使用真太阳时信息
    birth_year = record.solar_year if record.solar_year else record.birth_year
    birth_month = record.solar_month if record.solar_month else record.birth_month
    birth_day = record.solar_day if record.solar_day else record.birth_day
    birth_hour = record.solar_hour if record.solar_hour else record.birth_hour
    birth_minute = record.solar_minute if record.solar_minute else record.birth_minute
    
    birth_info = {
        'year': birth_year,
        'month': birth_month,
        'day': birth_day,
        'hour': birth_hour,
        'minute': birth_minute
    }
    
    async def generate_stream():
        full_content = ""
        try:
            chunk_count = 0
            # 在单独的线程中运行，避免阻塞事件循环
            loop = asyncio.get_event_loop()
            
            async for chunk in openai_service.analyze_bazi_stream(
                bazi_data, five_elements, birth_info, 
                name=record.name, gender=record.gender
            ):
                if chunk:
                    chunk_count += 1
                    full_content += chunk
                    yield f"data: {json.dumps({'type': 'content', 'text': chunk})}\n\n"
                    # 让出控制权，允许其他协程运行
                    await asyncio.sleep(0)
            
            # 如果没有收到任何内容，发送错误信息
            if not full_content and chunk_count == 0:
                # 回退到非流式分析，尽量给出结果
                try:
                    fallback = await openai_service.analyze_bazi(
                        bazi_data, five_elements, birth_info,
                        name=record.name, gender=record.gender
                    )
                    full_content = fallback or ""
                    if full_content:
                        yield f"data: {json.dumps({'type': 'content', 'text': full_content})}\n\n"
                    else:
                        error_msg = "AI分析失败，请稍后重试"
                        yield f"data: {json.dumps({'type': 'error', 'message': error_msg})}\n\n"
                        return
                except Exception as fb_err:
                    print(f"非流式回退失败: {fb_err}")
                    error_msg = "AI分析失败，请稍后重试"
                    yield f"data: {json.dumps({'type': 'error', 'message': error_msg})}\n\n"
                    return
            
            # 保存完整内容到数据库（数据库操作是异步安全的，不需要在线程池中）
            if full_content:
                try:
                    record.ai_analysis = full_content
                    record.stage = 2
                    db.commit()
                except Exception as db_error:
                    print(f"保存分析结果到数据库失败: {db_error}")
                    db.rollback()
            
            yield f"data: {json.dumps({'type': 'done'})}\n\n"
        except Exception as e:
            print(f"生成流式响应时出错: {e}")
            import traceback
            traceback.print_exc()
            # 发生异常时尝试回退到非流式
            try:
                fallback = await openai_service.analyze_bazi(
                    bazi_data, five_elements, birth_info,
                    name=record.name, gender=record.gender
                )
                if fallback:
                    yield f"data: {json.dumps({'type': 'content', 'text': fallback})}\n\n"
                else:
                    error_msg = f"AI分析过程中出错: {str(e)}"
                    yield f"data: {json.dumps({'type': 'error', 'message': error_msg})}\n\n"
            except Exception as fb_err:
                print(f"异常回退失败: {fb_err}")
                error_msg = f"AI分析过程中出错: {str(e)}"
                yield f"data: {json.dumps({'type': 'error', 'message': error_msg})}\n\n"
            finally:
                yield f"data: {json.dumps({'type': 'done'})}\n\n"
    
    # 添加SSE建议的响应头，提升稳定性
    headers = {
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "X-Accel-Buffering": "no"  # 关闭反向代理的缓冲
    }
    return StreamingResponse(generate_stream(), media_type="text/event-stream", headers=headers)

# 第二阶段：进行AI分析（非流式，用于兼容）
@app.post("/analyze-fortune/{record_id}", response_model=FortuneRecordSchema)
async def analyze_fortune(
    record_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """第二阶段：对已保存的记录进行AI分析"""
    # 获取记录
    record = db.query(FortuneRecord).filter(
        FortuneRecord.id == record_id,
        FortuneRecord.user_id == current_user.id
    ).first()
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="记录不存在"
        )
    
    # 如果已经分析过，直接返回
    if record.stage == 2 and record.ai_analysis:
        return record
    
    # 准备八字数据
    bazi_data = {
        'year_pillar': record.year_pillar,
        'month_pillar': record.month_pillar,
        'day_pillar': record.day_pillar,
        'hour_pillar': record.hour_pillar
    }
    
    # 分析五行
    five_elements = bazi_calculator.get_five_elements_analysis(bazi_data)
    
    # 使用真太阳时信息
    birth_year = record.solar_year if record.solar_year else record.birth_year
    birth_month = record.solar_month if record.solar_month else record.birth_month
    birth_day = record.solar_day if record.solar_day else record.birth_day
    birth_hour = record.solar_hour if record.solar_hour else record.birth_hour
    birth_minute = record.solar_minute if record.solar_minute else record.birth_minute
    
    birth_info = {
        'year': birth_year,
        'month': birth_month,
        'day': birth_day,
        'hour': birth_hour,
        'minute': birth_minute
    }
    
    # 使用 AI 分析
    ai_analysis = await openai_service.analyze_bazi(
        bazi_data, five_elements, birth_info, 
        name=record.name, gender=record.gender
    )
    
    # 更新记录
    record.ai_analysis = ai_analysis
    record.stage = 2  # 第二阶段完成
    
    db.commit()
    db.refresh(record)
    
    return record

# AI问答接口（流式）
@app.post("/ai-question/stream")
async def ai_question_stream(
    request: AIQuestionRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """AI问答功能（流式响应）"""
    # 获取记录
    record = db.query(FortuneRecord).filter(
        FortuneRecord.id == request.record_id,
        FortuneRecord.user_id == current_user.id
    ).first()
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="记录不存在"
        )
    
    # 准备八字数据
    bazi_data = {
        'year_pillar': record.year_pillar,
        'month_pillar': record.month_pillar,
        'day_pillar': record.day_pillar,
        'hour_pillar': record.hour_pillar
    }
    
    async def generate_stream():
        try:
            async for chunk in openai_service.answer_question_stream(
                bazi_data, request.question,
                name=record.name, gender=record.gender
            ):
                if chunk:
                    yield f"data: {json.dumps({'type': 'content', 'text': chunk})}\n\n"
                await asyncio.sleep(0)
            yield f"data: {json.dumps({'type': 'done'})}\n\n"
        except Exception as e:
            err_msg = f"AI问答过程中出错: {str(e)}"
            yield f"data: {json.dumps({'type': 'error', 'message': err_msg})}\n\n"
            yield f"data: {json.dumps({'type': 'done'})}\n\n"
    
    headers = {
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "X-Accel-Buffering": "no"
    }
    return StreamingResponse(generate_stream(), media_type="text/event-stream", headers=headers)

# AI问答接口（非流式，用于兼容）
@app.post("/ai-question", response_model=AIQuestionResponse)
async def ai_question(
    request: AIQuestionRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """AI问答功能"""
    # 获取记录
    record = db.query(FortuneRecord).filter(
        FortuneRecord.id == request.record_id,
        FortuneRecord.user_id == current_user.id
    ).first()
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="记录不存在"
        )
    
    # 准备八字数据
    bazi_data = {
        'year_pillar': record.year_pillar,
        'month_pillar': record.month_pillar,
        'day_pillar': record.day_pillar,
        'hour_pillar': record.hour_pillar
    }
    
    # 使用AI回答
    answer = await openai_service.answer_question(
        bazi_data, request.question,
        name=record.name, gender=record.gender
    )
    
    return AIQuestionResponse(answer=answer)

# 获取用户历史记录
@app.get("/fortune-records", response_model=List[FortuneRecordSchema])
async def get_fortune_records(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取用户历史记录"""
    records = db.query(FortuneRecord).filter(
        FortuneRecord.user_id == current_user.id
    ).order_by(FortuneRecord.created_at.desc()).all()
    
    return records

# 获取特定记录详情
@app.get("/fortune-records/{record_id}", response_model=FortuneRecordSchema)
async def get_fortune_record(
    record_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取特定记录详情"""
    record = db.query(FortuneRecord).filter(
        FortuneRecord.id == record_id,
        FortuneRecord.user_id == current_user.id
    ).first()
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="记录不存在"
        )
    
    return record

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8080)
